package com.z.ssmdemo.service.impl;

import com.z.platform.controller.persistence.ConnectionFactory;
import com.z.ssmdemo.service.LoginService;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import java.util.UUID;

/**
 * @author haonan.zhang
 */
public class LoginServiceImpl implements LoginService {
    @Override
    public String getUser(String nickName,String pazzword) {
        Statement statement = null;
        PreparedStatement preparedStatement = null;
        Connection conn =null;
        String name = null;
        String id = null;
        try {
            conn = ConnectionFactory.getConnection();
            //4.定义sql语句
            String sql = "SELECT * FROM  DEMO_USER where NickName = '" +  nickName + "'";
            // String sql ="SELECT d.* FROM  DEMO_USER d where NickName = 'zhangsan'";
            //5.获取执行sql的对象statement
            statement = conn.createStatement();
            //6.执行sql
            ResultSet rs = statement.executeQuery(sql);

            if (rs.next()){
                String dbNickName = rs.getString("nick_name");
                String dbPazzWord = rs.getString("pazz_word");
                if (dbNickName.equals(nickName) && dbPazzWord.equals(pazzword)){
                    id = rs.getString("id");
                    name = rs.getString("Name");
                    String sex = rs.getString("Sex");
                    Date regDate = rs.getDate("Reg_date");
                    Date brithDate = rs.getDate("Brith_date");
                }
            }else {
                sql = "insert into DEMO_USER(id,NickName,PazzWord,Name) values(?,?,?,?)";
                preparedStatement = conn.prepareStatement(sql);
                id = UUID.randomUUID().toString();
                preparedStatement.setString(1, id);
                preparedStatement.setString(2, nickName);
                preparedStatement.setString(3, pazzword);
                preparedStatement.setString(4, nickName);
                preparedStatement.executeUpdate();
            }

        }catch (Exception e) {
            //todo 后期添加日志记录异常
        }finally {
            try {
                //8.释放资源
                assert statement != null;
                statement.close();
                preparedStatement.close();
                conn.close();
            }catch (Exception e) {
                //todo 后期添加日志记录异常
            }

        }
        return name;
    }
}
